package org.jeecg.modules.workflow.framework.activiti.core.behavior;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.UserTask;
import org.flowable.common.engine.impl.el.ExpressionManager;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.util.TaskHelper;
import org.flowable.task.service.TaskService;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.jeecg.modules.workflow.service.definition.BpmTaskAssignRuleService;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


/**
 * 自定义的流程任务的 assignee 负责人的分配
 * 第一步，获得对应的分配规则；
 * 第二步，根据分配规则，计算出分配任务的候选人。如果找不到，则直接报业务异常，不继续执行后续的流程；
 * 第三步，随机选择一个候选人，则选择作为 assignee 负责人。
 *
 * @author 芋道源码
 */
@Slf4j
public class BpmUserTaskActivitiBehavior extends UserTaskActivityBehavior {

    @Setter
    private BpmTaskAssignRuleService bpmTaskRuleService;


    public BpmUserTaskActivitiBehavior(UserTask userTask) {
        super(userTask);
    }

    @Override
    protected void handleAssignments(TaskService taskService,
                                     String assignee, String owner, List<String> candidateUsers, List<String> candidateGroups,
                                     TaskEntity task, ExpressionManager expressionManager, DelegateExecution execution, ProcessEngineConfigurationImpl processEngineConfiguration) {
        if (super.multiInstanceActivityBehavior != null) {
            String assigneeUserId = execution.getVariable(super.multiInstanceActivityBehavior.getCollectionElementVariable(), String.class);
            Assert.notNull(assigneeUserId, "任务处理人不能为空");
            TaskHelper.changeTaskAssignee(task, assigneeUserId);
        }else{
            List<String> candidateUserIds = bpmTaskRuleService.calculateTaskCandidateUsers(execution);
            if(1 == candidateUserIds.size()){
                TaskHelper.changeTaskAssignee(task, String.valueOf(candidateUserIds.iterator().next()));
                return;
            }

            //根据页面选择类型(用户,角色),设置候选人,候选组
            List<String> candidateCustoms = new ArrayList<>();
            for (String candidate : candidateUserIds) {
                candidateCustoms.add(candidate + "");
            }

            super.handleAssignments(taskService, assignee, owner, candidateCustoms, candidateGroups, task, expressionManager, execution,processEngineConfiguration);

        }
    }

}
